﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ArticleWeb.Models;

namespace ArticleWeb.Controllers
{
    [Authorize]
    public class ArticleCategoriesController : Controller
    {
        public ActionResult UpdateTreeItem(int id, int? parent, int position)
        {
            var model = db.ArticleCategories.Find(id);
            model.ParentID = parent;
            db.Entry(model).State = EntityState.Modified;
            db.SaveChanges();
            return this.JsonOk();
        }
        private ApplicationDbContext db = new ApplicationDbContext();
        [AllowAnonymous]
        public ActionResult GetJson()
        {
            var d = db.ArticleCategories.Select(x => new
            {
                id = x.ID.ToString(),
                //parent = x.ParentID.HasValue ? x.ParentID.ToString() : "#",
                text = x.Name
            }).ToList();
            return this.JsonOk(d, JsonRequestBehavior.AllowGet);
        }
        [AllowAnonymous]
        public ActionResult GetHtml()
        {
            return PartialView(_GetTreeNodes(null));
        }
        public ActionResult GetJsTreeItems()
        {
            //var selectSql = "SELECT ID,CASE WHEN PARENTID IS NULL THEN '#' ELSE convert(varchar(20),PARENTID) AS PARENT,Name as TEXT";
            var d = db.ArticleCategories.ToList();
            var dJson = d.Select(x => new JsTreeItem
            {
                id = x.ID.ToString(),
                parent = x.ParentID.HasValue ? x.ParentID.ToString() : "#",
                text = x.Name
            }).ToList();

            var rootList = d.Where(x => x.ParentID == null);
            foreach (var item in rootList)
            {
                var second = _GetSubCategoryIds(d, item.ID);
                foreach (var s in second)
                {
                    var s_third = _GetSubCategoryIds(d, s);
                    dJson[dJson.FindIndex(x => x.id == s.ToString())].text += $"({db.Articles.Count(x => s_third.Contains(x.CatagoryID))})";
                    foreach (var t in s_third)
                    {
                        dJson[dJson.FindIndex(x => x.id == t.ToString())].text += $"({db.Articles.Count(x => x.CatagoryID == t)})";
                    }
                }
                var ids = second.SelectMany(x => _GetSubCategoryIds(d, x));
                dJson[dJson.FindIndex(x => x.id == item.ID.ToString())].text += $"({db.Articles.Count(x => ids.Contains(x.CatagoryID))})";
            }
            return this.JsonOk(dJson);
        }
        private List<int> _GetSubCategoryIds(List<ArticleCategory> list, int catId)
        {
            return list.Where(x => x.ParentID == catId).Select(x => x.ID).ToList();
        }
        private List<TreeNode> _GetTreeNodes(int? parentId)
        {
            var list = db.ArticleCategories.Where(x => x.ParentID == parentId).Select(x => new TreeNode { id = x.ID, name = x.Name, spread = true, parent = x.ParentID }).ToList();
            foreach (var item in list)
            {
                item.children = _GetTreeNodes(item.id);
            }
            return list;
        }

        public ActionResult GetTreeNodes()
        {
            return this.JsonOk(_GetTreeNodes(null));
        }

        // GET: ArticleCategories
        public ActionResult Index(int page = 1)
        {
            ViewBag.AllList = db.ArticleCategories.Select(x => new IDNameNode { ID = x.ID, Name = x.Name, ParentId = x.ParentID }).ToList();
            ViewBag.RootList = db.ArticleCategories.Where(x => x.ParentID == null).Select(x => new IDName { ID = x.ID, Name = x.Name }).ToList();
            var query = db.ArticleCategories.OrderBy(x => x.ID);
            ViewBag.Total = query.Count();
            return View(query.ToList(page));
        }

        // GET: ArticleCategories/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ArticleCategory articleCategory = db.ArticleCategories.Find(id);
            if (articleCategory == null)
            {
                return HttpNotFound();
            }
            return View(articleCategory);
        }


        public ActionResult Exists(int? id, string newName)
        {
            if (string.IsNullOrEmpty(newName))
            {
                return this.JsonError("分类名称不能为空");
            }
            if (id == null)//when create new
            {
                if (db.ArticleCategories.Any(x => x.Name == newName))
                {
                    return this.JsonDuplicate();
                }
                else
                    return this.JsonOk();
            }
            else // when modify name
            {
                if (db.ArticleCategories.Any(x => x.Name == newName && x.ID != id))
                {
                    return this.JsonDuplicate();
                }
                else
                    return this.JsonOk();
            }
        }
        public ActionResult Create(int? parentId)
        {
            return View();
        }

        // POST: ArticleCategories/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,Name,ParentId")] ArticleCategory model)
        {
            if (ModelState.IsValid)
            {
                db.ArticleCategories.Add(model);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(model);
        }

        // GET: ArticleCategories/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ArticleCategory model = db.ArticleCategories.Find(id);
            if (model == null)
            {
                return HttpNotFound();
            }
            return View(model);
        }

        // POST: ArticleCategories/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Name")] ArticleCategory model)
        {
            if (ModelState.IsValid)
            {
                var m = db.ArticleCategories.Find(model.ID);
                m.Name = model.Name;
                db.Entry(m).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(model);
        }

        // GET: ArticleCategories/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            ArticleCategory articleCategory = db.ArticleCategories.Find(id);
            if (articleCategory == null)
            {
                return HttpNotFound();
            }
            return View(articleCategory);
        }

        // POST: ArticleCategories/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            ArticleCategory articleCategory = db.ArticleCategories.Find(id);
            db.ArticleCategories.Remove(articleCategory);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
